package org.xiaojinlong.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NIOSocket {
    public static void main(String[] args) throws IOException {
        // 创建一个选择器 可用close()关闭
        Selector selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress("127.0.0.1", 5432));
        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select() == 0) continue;
            Set<SelectionKey> keys = selector.selectedKeys();
            for (SelectionKey key: keys) {
                // OP_ACCEPT这个只有ServerSocketChannel才有可能触发
                if (key.isAcceptable()) {
                    SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
                    channel.configureBlocking(false);
                    channel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    channel.read(buffer);
                    key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                }
                keys.remove(key);
            }

        }
    }
}
